package tree;

import java.util.Stack;

/**
 * 530. 二叉搜索树的最小绝对差
 * 二叉搜索树一定是中序遍历
 * @author Api
 * @date 2023/10/26 22:54
 */
public class Code530_MinimumAbsoluteDifferenceOfBinarySearchTree {
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int result = Integer.MAX_VALUE;
    TreeNode pre = null; // 前一个节点

    public int getMinimumDifference(TreeNode root) {
        traversal(root);
        return result;
    }

    // 中序遍历
    public void traversal(TreeNode cur) {
        if (cur == null) {
            return;
        }
        // 左
        traversal(cur.left);
        // 中
        if (pre != null) {
            result = Math.min(result, cur.val - pre.val);
        }
        pre = cur;
        traversal(cur.right);
    }

    // 迭代法-中序遍历
    TreeNode prev;
    Stack<TreeNode> stack;

    public int getMinimumDifference1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        stack = new Stack<>();
        TreeNode cur = root;
        int result = Integer.MAX_VALUE;
        while (cur != null || !stack.isEmpty()) {
            if (cur != null) {
                stack.push(cur); // 将访问的节点放进栈
                cur = cur.left; // 左
            } else {
                cur = stack.pop();
                if (pre != null) { // 中
                    result = Math.min(result, cur.val - pre.val);
                }
                pre = cur;
                cur = cur.right;
            }
        }
        return result;
    }
}
